package com.jxs.android.cmcc;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.jxs.android.cmcc.boot.SelfApplication;
import com.jxs.android.cmcc.data.MenuInfo;
import com.jxs.android.cmcc.data.UserInfo;
import com.jxs.android.cmcc.db.InterfaceHolder;
import com.jxs.android.cmcc.db.KipConfigHolder;
import com.jxs.android.cmcc.db.MenuHolder;
import com.jxs.android.cmcc.db.SystemParamHolder;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.util.CryptUtil;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.util.SysUpdateHolder;
import com.jxs.android.util.VersionHolder;
import com.jxs.android.weiget.GesturePwdView;
import com.jxs.android.weiget.GesturePwdView.GesturePwdListener;
import com.jxs.android.weiget.PopMsg;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
public class LoginBak extends AbstractActivity {

	private GesturePwdView gesture_pwd;
	private Context context;
	private ProgressDialog progressDialog;
	private String imsi = "460030309442061";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;

		super.initTopBar(savedInstanceState, R.layout.bu_login_bak);

		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		imsi = null == tm.getSubscriberId() ? "" : tm.getSubscriberId();
		if (StringUtils.isEmpety(imsi)) {
			PopMsg.show("请插入SIM卡！");
			finish();
		}
		imsi = "460030309442061";

		gesture_pwd = (GesturePwdView) this.findViewById(R.id.gesture_pwd);
		gesture_pwd.setGesturePwdListener(new GesturePwdListener() {
			@Override
			public void onComplete(String mPassword) {
				Log.e("Password", "" + mPassword);
				gesture_pwd.clearPassword();
				progressDialog = ProgressDialog.show(context, "", "登录中，请稍候...", true);
				progressDialog.setCancelable(true);
				login(mPassword);
			}

			@Override
			public int minPwdLength() {
				return 5;
			}

			@Override
			public void error() {
				Toast.makeText(context, "长度太短了", Toast.LENGTH_LONG).show();
			}

		});

	}

	private void login(final String password) {
		final CryptUtil crypt = CryptUtil.getInstance();
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = SelfApplication.WSDL_URL;// wsdl
				String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "login";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("password", crypt.encryptAES(password, CryptUtil.getKey()));

				request.addProperty("imsiCode", crypt.encryptAES(imsi, CryptUtil.getKey()));
				request.addProperty("imeiCode", crypt.encryptAES(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId(), CryptUtil.getKey()));
				request.addProperty("systemVersion", android.os.Build.VERSION.RELEASE);
				request.addProperty("clientVersion", VersionHolder.getVersionName(context));
				request.addProperty("longitude", "105");
				request.addProperty("latitude", "44");
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paserLogin(response);
					}
				});
			}
		}).start();
	}

	private void paserLogin(SoapObject soapObject) {
		String stauts = soapObject.getPropertySafelyAsString("status");
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getPropertySafelyAsString("message");
		if ("-2".equals(stauts)) {
			Message msg = new Message();
			msg.what = UPDATE_VERSION;
			String objs[] = new String[2];
			objs[0] = message;
			objs[1] = soapObject.getPropertySafelyAsString("url");
			msg.obj = objs;
			handler.sendMessage(msg);
		} else if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("0".equals(stauts)) {
			SoapObject userObject = (SoapObject) soapObject.getProperty("user");
			if (null != userObject) {
				UserInfo userInfo = new UserInfo();
				userInfo.setImsi(userObject.getPropertySafelyAsString("imsi"));
				userInfo.setOrg_id(userObject.getPropertySafelyAsString("org_id"));
				userInfo.setOrg_name(userObject.getPropertySafelyAsString("org_name"));
				userInfo.setPhone_number(userObject.getPropertySafelyAsString("phone_number"));
				userInfo.setTicket(userObject.getPropertySafelyAsString("ticket"));
				userInfo.setUser_name(userObject.getPropertySafelyAsString("user_name"));

				SelfApplication.setUserInfo(userInfo);
				initConfigData(soapObject, message);
			}
		}
	}

	private void initConfigData(final SoapObject soapObject, final String message) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				SoapObject configObject = (SoapObject) soapObject.getProperty("config");
				if (null != configObject) {
					String menu_update_date = SystemParamHolder.getParamValue(SystemParamHolder.Keys.MENU_UPDATE_DATE);
					if (StringUtils.isEmpety(menu_update_date) || !menu_update_date.equals(configObject.getPropertySafelyAsString("menu_update_date"))) {
						SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.MENU_UPDATE_DATE, configObject.getPropertySafelyAsString("menu_update_date"));
						getMenuList();
					}

					// 报表更新日期列表
					SoapObject tableConfigObject = (SoapObject) configObject.getProperty("table_date_list");
					initTableConfigObject(tableConfigObject);

					// 指标更新日期列表
					SoapObject kpiConfigObject = (SoapObject) configObject.getProperty("kpi_date_list");
					initKpiConfigObject(kpiConfigObject);

					Message msg = new Message();
					msg.what = LOGIN_ON;
					msg.obj = message;
					handler.sendMessage(msg);
				}
			}
		}).start();

	}

	private void getMenuList() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = SelfApplication.WSDL_URL;// wsdl
				String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "getMenuList";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("ticket", SelfApplication.getUserInfo().getTicket());
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paserMenu(response);
					}
				});
			}
		}).start();
	}

	private void paserMenu(SoapObject soapObject) {
		String stauts = soapObject.getPropertySafelyAsString("status");
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getPropertySafelyAsString("message");
		if ("0".equals(stauts)) {
			SoapObject menuSoapObject = (SoapObject) soapObject.getProperty("retMsg");
			if (null != menuSoapObject) {
				for (int i = 0; i < menuSoapObject.getPropertyCount(); i++) {
					SoapObject menuBeanObject = (SoapObject) menuSoapObject.getProperty(i);
					MenuInfo menuInfo = new MenuInfo();

					menuInfo.setMenu_id(menuBeanObject.getPropertySafelyAsString("menu_id"));
					menuInfo.setMenu_name(menuBeanObject.getPropertySafelyAsString("menu_name"));
					menuInfo.setSuper_menu(menuBeanObject.getPropertySafelyAsString("super_menu"));
					menuInfo.setMenu_lvl(menuBeanObject.getPropertySafelyAsString("menu_lvl"));
					menuInfo.setMenu_pic_name(menuBeanObject.getPropertySafelyAsString("menu_pic_name"));
					menuInfo.setMenu_pos(menuBeanObject.getPropertySafelyAsString("menu_pos"));
					menuInfo.setMenu_style(menuBeanObject.getPropertySafelyAsString("menu_style"));
					menuInfo.setIsnew(menuBeanObject.getPropertySafelyAsString("isnew"));
					menuInfo.setInterface_id(menuBeanObject.getPropertySafelyAsString("interface_id"));

					MenuHolder.saveOrUpdate(menuInfo);

					localMenu();

					for (int j = 0; j < 10; j++) {
						MenuInfo info = new MenuInfo();
						info.setMenu_id(j + "__d-d");
						info.setMenu_lvl("1");
						info.setInterface_id(j + "");
						info.setMenu_name("翻页" + i + j);
						info.setMenu_pos("999");
						info.setMenu_pic_name("1.png");
						MenuHolder.saveOrUpdate(info);
					}
				}
			}

		} else {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		}
	}

	private void localMenu() {

		MenuInfo info = new MenuInfo();

		info.setMenu_id("notice");
		info.setMenu_lvl("1");
		info.setInterface_id("");
		info.setMenu_name(getString(R.string.notice_title_label));
		info.setMenu_pos("80");
		info.setMenu_pic_name("notice.png");
		MenuHolder.saveOrUpdate(info);

		info = new MenuInfo();
		info.setMenu_id("help");
		info.setMenu_lvl("1");
		info.setInterface_id("");
		info.setMenu_name(getString(R.string.help_title_label));
		info.setMenu_pos("81");
		info.setMenu_pic_name("help.png");
		MenuHolder.saveOrUpdate(info);

	}

	private void initTableConfigObject(SoapObject tableConfigObject) {
		for (int i = 0; i < tableConfigObject.getPropertyCount(); i++) {
			SoapObject tableBeanObject = (SoapObject) tableConfigObject.getProperty(i);
			String interface_id = tableBeanObject.getPropertySafelyAsString("interface_id");
			String stat_date = tableBeanObject.getPropertySafelyAsString("stat_date");
			InterfaceHolder.saveOrUpdate(interface_id, stat_date);
		}
	}

	private void initKpiConfigObject(SoapObject kpiConfigObject) {
		for (int i = 0; i < kpiConfigObject.getPropertyCount(); i++) {
			SoapObject kipBeanObject = (SoapObject) kpiConfigObject.getProperty(i);
			String kpi_id = kipBeanObject.getPropertySafelyAsString("kpi_id");
			String stat_date = kipBeanObject.getPropertySafelyAsString("stat_date");
			KipConfigHolder.saveOrUpdate(kpi_id, stat_date);
		}
	}

	private int LOGIN_ON = 0x110;
	private int UPDATE_VERSION = 0x111;
	private int ERROR_MSG = 0x112;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.cancel();
			}
			if (msg.what == LOGIN_ON) {
				// PopMsg.show((String) msg.obj);
				StartHelper.startActivity(new Intent(context, Laucher.class));
				finish();
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == UPDATE_VERSION) {
				String objs[] = (String[]) msg.obj;
				SysUpdateHolder.showUpdataDialog(LoginBak.this, objs[0], "下载新版本", objs[1], new SysUpdateHolder.UpdateCancelListern() {

					@Override
					public void cancel() {
						// StartHelper.startActivity(new Intent(context,
						// Laucher.class));
						finish();
					}
				});
			}
		}

	};

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarLogic(topBar);
		topBar.hindSelf();
	}

}